package feiyi

import (
	"github.com/Aiicy/htmlquery"
	"github.com/ruoklive/proxypool/internal/ipgetter/base"
	"github.com/ruoklive/proxypool/pkg/models"
	"github.com/ruoklive/proxypool/pkg/register"
	"go.uber.org/zap"
	"io"
)

func init() {
	register.Add(func() register.IPGetter {
		return New()
	})
}

type IPGetter struct {
	base.Base
}

func New() *IPGetter {
	g := &IPGetter{}
	g.Base = base.NewBase("http://www.feiyiproxy.com/?page_id=1457",g.Parse,"Feiyi")
	return g
}


func (g *IPGetter) Parse(body io.ReadCloser) (result []*models.IP) {
	doc, err := htmlquery.Parse(body)
	if err != nil {
		g.Error("Parse fail!",zap.Error(err))
		return
	}
	trNode, err := htmlquery.Find(doc, "//div[@class='et_pb_code et_pb_module  et_pb_code_1']//div//table//tbody//tr")
	if err != nil {
		g.Error("Parse fail!",zap.Error(err))
		return
	}
	for i := 1; i < len(trNode); i++ {
		tdNode, _ := htmlquery.Find(trNode[i], "//td")
		if len(tdNode) < 7 {
			continue
		}
		if htmlquery.InnerText(tdNode[2]) != "高匿" {
			continue
		}
		ip := htmlquery.InnerText(tdNode[0])
		port := htmlquery.InnerText(tdNode[1])
		Type := htmlquery.InnerText(tdNode[3])
		speed := htmlquery.InnerText(tdNode[6])

		IP := models.NewIP()
		IP.Data = ip + ":" + port

		if Type == "HTTPS" {
			IP.Type1 = "https"
			IP.Type2 = ""

		} else if Type == "HTTP" {
			IP.Type1 = "http"
		}
		IP.Speed = g.ExtractSpeed(speed)

		g.Debug("GET IP",zap.String("ip",IP.String()))

		result = append(result, IP)
	}
	g.Info("done.")
	return
}


